package com.example.xwadmin.api.interceptor;

import com.example.xwcommon.annotation.Allow;
import com.example.xwcommon.annotation.Login;
import com.example.xwcommon.entity.Admin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AllowInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Allow allow=null;
        if(handler instanceof HandlerMethod){
            HandlerMethod m=(HandlerMethod)handler;
            allow = m.getMethodAnnotation(Allow.class);
            if(allow == null){
                return true;
            }
        }
        String[] roles=allow.roles();
        String[] pmses=allow.pmses();

        Admin admin=(Admin) request.getAttribute("cur_admin");
        for(String role:roles){//角色是否包含
            if(admin.getLevel().contains(role)){
                return true;
            }
        }
        for(String pmse:pmses){//角色是否包含
            if(admin.getPmses().contains(pmse)){
                return true;
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"code\":4001,\"msg\":\"权限不足\"}");
        response.setStatus(403);
        return false;
    }
}
